export default {

  buildTree(items, idKey="id", parentKey="parentId", childrenKey="children") {
    const map = {};
    const tree = [];
  // 创建所有节点的映射
    items.forEach(item => {
      map[item[idKey]] = {...item, [childrenKey]: []};
    });

  // 构建树形结构
    items.forEach(item => {
      const node = map[item[idKey]];
      const parentId = item[parentKey];

    // 如果父节点存在，就把节点加入到父节点的children
      if (parentId && map[parentId]) {
        map[parentId].children.push(node)
      } else {
        // 没有父节点或父节点不存在，作为根节点
        tree.push(node)
      }
    })

    return tree;
  },

  // 递归排序树形节点
  sortTree(nodes, sortKey="orderNum", sortDirection = "asc", childrenKey="children") {
    if (!nodes || nodes.length === 0) {
      return [];
    }

    // 排序当前层节点
    const sorted = [...nodes].sort((a, b) => {
      if (sortDirection === "asc") {
        return a[sortKey] - b[sortKey];
      } else {
        return b[sortKey] - a[sortKey];
      }
    });

    // 递归排序子节点
    sorted.forEach(node => {
      if (node[childrenKey] && node[childrenKey].length > 0) {
        node[childrenKey] = this.sortTree(node[childrenKey]);
      }
    });

    return sorted;
  }

}
